import React, { useEffect, useState } from 'react';
import { Layout, Menu } from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import styles from './index.css';

const { Header, Content } = Layout;

const BasicLayout = (props) => {
  const { dispatch, Global } = props;
  const { app = {} } = Global;

  const [selectedMenu, setSelectedMenu] = useState('');

  useEffect(() => {
    dispatch({
      type: 'Global/fetchApp',
      callback: () => {
        setSelectedMenu('/' + props.location.pathname.split('/')[1] + '/');
      },
    });
  }, [dispatch, props.location.pathname]);

  /**
   * 渲染子应用菜单
   * @param key
   * @param index
   * @returns {*}
   */
  function renderSubAppMenu (key, index) {
    return (
      <Menu.Item key={ key }>
        { app[key].menuName }
      </Menu.Item>
    );
  }

  /**
   * 子应用点击
   * @param e
   */
  function onMenuItemClick (e) {
    setSelectedMenu(e.key);
    router.push(e.key);
  }

  return (
    <Layout style={ { minHeight: '100vh' } }>
      <Header>
        <div className={ styles.logo }/>
        <Menu style={ { lineHeight: '64px' } } mode="horizontal" theme={ 'dark' } onClick={ onMenuItemClick }
              selectedKeys={ [selectedMenu] }>
          { Object.keys(app).map((key, index) => renderSubAppMenu(key, index)) }
        </Menu>
      </Header>
      <Content>
        { app['/' + props.location.pathname.split('/')[1] + '/'] ? null : props.children }
        <div id="root-slave"></div>
      </Content>
    </Layout>
  );
};

function mapStateToProps ({ Global, loading }) {
  return {
    Global,
    loading: loading.effects['Global/fetchApp'],
  };
}

export default connect(mapStateToProps)(BasicLayout);
